import { ProList } from '@ant-design/pro-components';
import type { ProFormInstance } from '@ant-design/pro-form';
import { DrawerForm, ProFormDigit, ProFormSelect } from '@ant-design/pro-form';
import { Button, Space, Statistic, Tag } from 'antd';
import { useRef, useState } from 'react';
import { hotProductList } from '../service';

export type FormValueType = {
  hotCount?: number;
  channel?: string;
  products?: [];
};
/**
 * 获取热销商品名称列表
 * @param data 商品数据数组
 * @param topN 可选参数，指定返回前N个热销商品
 * @returns 返回按订单量排序的商品信息数组，包含商品名称、评分和订单量
 */
const getTopProductNames = async (data: [any], topN?: number) => {
  // 1. 按照 orders 从大到小排序
  const sortedData = [...data].sort((a, b) => b.orders - a.orders);

  // 2. 取出 productName
  let result = sortedData.map((item) => ({
    appLink: item.appLink,
    rate: item.rate,
    orders: item.orders,
  }));
  // 3. 如果指定了 topN，则截取前 N 个
  if (topN !== undefined && topN > 0) {
    result = result.slice(0, topN);
  }

  return result;
};
function mergeAndSortOrders(data: any, topN?: number) {
    const ordersMap = new Map<string, number>();

    // 遍历数据，累加相同shopName的orders
    data.forEach((item:any) => {
        const { roomName, orders } = item;
        if (ordersMap.has(roomName)) {
            ordersMap.set(roomName, ordersMap.get(roomName)! + orders);
        } else {
            ordersMap.set(roomName, orders);
        }
    });

    // 转换为数组并排序
    let result = Array.from(ordersMap, ([roomName, orders]) => ({ roomName, orders }));
    result.sort((a, b) => b.orders - a.orders);
    if (topN !== undefined && topN > 0) {
      result = result.slice(0, topN);
    }
    return result;
}
export type HotProductFormProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: FormValueType) => Promise<void>;
  visible: boolean;
  values?: Partial<FormValueType>;
};

const cpsConf = [
  { label: 'APP_2', value: 'CPS-ZBJ-yf2' },
  { label: 'APP_3', value: 'CPS-ZBJ-yf3' },
  { label: 'APP_4', value: 'CPS-ZBJ-yf4' },
  { label: 'APP_5', value: 'CPS-ZBJ-yf5' },
  { label: 'APP_6', value: 'CPS-ZBJ-yf6' },
  { label: 'APP_7', value: 'CPS-ZBJ-yf7' },
];

const HotProductForm: React.FC<HotProductFormProps> = (props) => {
  const formRef = useRef<ProFormInstance>();
  const [hotCount, setHotCount] = useState(props.values?.hotCount);
  const [commands, setCommands] = useState([]);
  const [channel, setChannel] = useState(props.values?.channel);
  return (
    <DrawerForm
      title="爆品合集"
      width={620}
      formRef={formRef}
      visible={props.visible}
      onVisibleChange={(visible) => {
        if (!visible) {
          props.onCancel(false);
        }
      }}
      // onFinish={async (values) => {
      //   await props.onSubmit(values);
      //   return true;
      // }}
      initialValues={props.values}
      submitter={{
        // 完全自定义底部按钮区域
        render: () => {
          return [
            <Button
              key="cancel"
              onClick={() => {
                props.form?.resetFields();
                props.onCancel(false);
              }}
            >
              取消
            </Button>,
            <Button
              key="submit"
              type="primary"
              onClick={async () => {
                console.log(commands)
                await props.onSubmit(commands);
                return true;
              }}
            >
              获取口令
            </Button>,
          ];
        },
      }}
    >
      <ProFormDigit
        name="hotCount"
        label="热卖个数"
        min={1}
        max={100}
        fieldProps={{
          style: { width: '100%' },
          placeholder: '请输入热卖个数',
        }}
        onChange={(e) => {
          setHotCount(e);
        }}
        rules={[{ required: true, message: '请输入热卖个数' }]}
      />

      <ProFormSelect
        name="channel"
        label="渠道选择"
        options={cpsConf}
        fieldProps={{
          optionLabelProp: 'label',
        }}
        onChange={(e) => {
          setChannel(e);
        }}
        rules={[{ required: true, message: '请至少选择一个渠道' }]}
      />
      <Button
        type="primary"
        onClick={async () => {
          const product = await mergeAndSortOrders(props.values.products, hotCount);
          const rsp = await hotProductList({ channel: channel, list: product });
          if (rsp.code === 'SUCCESS') {
            setCommands(rsp.data);
          }
        }}
      >
        生成
      </Button>
      <ProList<any>
        rowKey="id"
        headerTitle="商品列表"
        dataSource={commands}
        metas={{
          title: {
            dataIndex: 'productName',
          },
          description: {
            render: (_, record) => (
              <>
                <Space size="small">
                  <Tag color="blue">后台佣金: {record.rate}</Tag>
                  {record.subRate !== null && <Tag color="green">佣金比例: {record.subRate}</Tag>}
                </Space>
                <Space>
                  <Tag color="red">小程序口令: {record.url}</Tag>
                </Space>
              </>
            ),
          },
          extra: {
            render: (_, record) => (
              <Statistic
                title="订单数"
                value={record.order}
                precision={0}
                valueStyle={{ color: '#3f8600' }}
              />
            ),
          },
        }}
      />
    </DrawerForm>
  );
};

export default HotProductForm;
